﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Shapes
{
  public partial class Circle : UserControl
  {
		private bool _selected;

    public Circle()
    {
      InitializeComponent();
    }

		public PartnersContainer Partners
		{
			get;
			set;
		}

		public void Rotate(Circle centre, Circle partner, double angle)
		{
			double distance = Math.Sqrt(Math.Pow(Left - centre.Left, 2) + Math.Pow(Top - centre.Top, 2)) * -1;

			Left = centre.Left + (int)Math.Round(distance * Math.Cos(angle));
			Top  = centre.Top - (int)Math.Round(distance * Math.Sin(angle));

			for (int i = 0; i < Partners.Count; i++)
				if (Partners[i] != partner)
					Partners[i].Rotate(centre, this, angle);
		}

		public void Rotate(Circle partner, int x, int y)
		{
			if (!Selected)
				return;

			int halfWidth = Width / 2;
			double distance = Math.Sqrt(Math.Pow(Left - partner.Left, 2) + Math.Pow(Top - partner.Top, 2)) * -1;
			double angle = -Math.Atan2(partner.Top + halfWidth - y, partner.Left + halfWidth - x);

			Left = partner.Left + (int)Math.Round(distance * Math.Cos(angle));
			Top  = partner.Top  - (int)Math.Round(distance * Math.Sin(angle));

			for (int i = 0; i < Partners.Count; i++)
				if (Partners[i] != partner)
					Partners[i].Rotate(partner, this, angle);
		}

		public bool Selected
		{
			get
			{
				return _selected;
			}
			set
			{
				_selected = value;
				UpdateColor();
			}
		}

		private void UpdateColor()
		{
			//BackColor = Selected ? Color.Red : Color.Green;
		}

    private void UserControl1_Load(object sender, EventArgs e)
    {
      UpdateRegion();
			Partners = new PartnersContainer();
			Selected = false;
    }

    private void UpdateRegion()
    {
			GraphicsPath graphicsPath = new GraphicsPath();
      graphicsPath.AddEllipse(0, 0, this.Width, this.Height);
      Region = new Region(graphicsPath);
    }

    private void UserControl1_Resize(object sender, EventArgs e)
    {
      UpdateRegion();
      this.Width = this.Height;
    }

		private void UserControl1_MouseDown(object sender, MouseEventArgs e)
		{
			Selected = true;
		}

		private void UserControl1_MouseUp(object sender, MouseEventArgs e)
		{
			Selected = false;
		}
  }
}
